package com.wenjing.xiaoyun.chat.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author jiangshizhang
 * @version 1.0
 * @description: 返回照片接口
 * @date 2025/5/26 15:55
 */
@RestController
@RequestMapping("/images")
public class ImageController {

    private static final String IMAGE_DIRECTORY = "D:/output/";

    /**
     * 输出本地文件信息 有资源可以扩展为nas、s3
     *
     *
     * @param filename 文件信息
     * @return 本地文件
     */
    @GetMapping("/{filename}")
    public ResponseEntity<Resource> getImage(@PathVariable String filename) {
        try {
            Path imagePath = Paths.get(IMAGE_DIRECTORY).resolve(filename);
            File imageFile = imagePath.toFile();

            if (!imageFile.exists() || !imageFile.isFile()) {
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(imageFile);

            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);

        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
}